<?php

require_once 'mobile_functions.php';
require_once 'small_actions.php';

//function countNewNotifs() {#this fucntion is called by server_index and we dont want to import mobile_functions in server_index coz we imported index which imports mobile functions, obviously require_once might solve this but lets be clean: simon 28may2012 3:50am
//    return numOfNewNotifs();
//}

function fetchJson() {
    $state = $_GET['state'];
    $finalStr = "";
    if ($state == "enroll_home") {
        $finalStr.="{list:{title:'Select a course to enroll', list_id:'enrollList', items: [";
        $finalStr.=getEnrolledCourses(phoneNoToUserID($_GET['phone_number']), FALSE);
        $finalStr.="]}}";
    } else if ($state == "courses_home") {
        $finalStr.="{list:{title:'Select a course', list_id:'courseList', items: [";
        $finalStr.=getEnrolledCourses(phoneNoToUserID($_GET['phone_number']), TRUE, "false");
        $finalStr.="],message:{text:'Quizes are available for Done courses.'}";
        $finalStr.="}}";
    } else if ($state == "quizes_home") {
        $finalStr.="{list:{title:'Select a course to do quizes', list_id:'courseQuizList', items: [";
        $finalStr.=getEnrolledCourses(phoneNoToUserID($_GET['phone_number']), TRUE, "true");
        $finalStr.="]}}";
    } else if ($state == "download_home") {
        $finalStr.="{courses:'";
        $finalStr.=downloadEnrolledCourses(phoneNoToUserID($_GET['phone_number']), TRUE);
        $finalStr.="'}";
    } else if ($state == "interaction_home") {
        if (hasAcceptCondtion ()) {
            $finalStr.=getInteractionHome();
        } else {
            $finalStr.="{form:{title:'Terms and Conditions', form_id:'termsAndConditions', items:[";
            $finalStr.="{label:{text:'" . getTerms() . "'}},";
            $finalStr.="{checkbox:{id:'accept', label:'Accept'}}";
            $finalStr.="]}}";
        }
    } else if ($state == "notifications_home") {
        $finalStr.=getNotoficationsList();
    } else if ($state == "download_lessons") {
        $finalStr.="{lessons:'";
        $finalStr.=downloadLessons($_GET['course_id']);
        $finalStr.="'}";
    } else if ($state == "download_pages") {
        $finalStr.="{pages:'";
        $finalStr.=downloadPages($_GET['lesson_id']);
        $finalStr.="'}";
//	echo $finalStr;
    } else if ($state == "select") {
        $list_id = $_GET['list_id'];
        if ($list_id == "enrollList") {
            $sid = $_GET['sid'];
            $finalStr.="{form:{title:'Confirm Enrollement', form_id:'confirmEnroll$sid', items:[";
            $finalStr.="{label:{text:'Are sure to enroll in -" . getCourse($sid) . "- '}},";
            $finalStr.="{checkbox:{id:'enroll', label:'Enroll'}}";
            $finalStr.="]}}";
        } else if ($list_id == "courseList") {
            $course_id = $_GET['sid'];
            $finalStr.="{list:{title:'Select a Lesson', list_id:'lessonList', items: [";
            $finalStr.=getLessons($course_id, phoneNoToUserID($_GET['phone_number']));
            $finalStr.="]";
            $done = courseDone($course_id, phoneNoToUserID($_GET['phone_number']));
//            var_dump($done);
            if ($done) {
                $finalStr.=",message:{text:'All the questions in this course have been completed, you can proceed to the quiz.'}";
            }
            $finalStr.="}}";
//            var_dump($finalStr);
        } else if ($list_id == "blogList") {
            $course_id = $_GET['sid'];
            $finalStr.=getBlogActionList($course_id);
        } else if (preg_match("/^blogActionList/i", $list_id)) {
            $course_id = substr($list_id, strlen("blogActionList"));
            $actionId = $_GET['sid'];
            if ($actionId == "addBlogQuestion") {
                $finalStr.="{form:{title:'Create a topic', form_id:'addBlogQuestion$course_id', items:[";
                $finalStr.= "{textfield:{id:'blogQuestionText',label:'Topic'}},";
                $finalStr.="]}}";
            } else if ($actionId == "viewBlogQuestions") {
                $finalStr.="{list:{title:'Select a topic', list_id:'blogQuestionList', items: [";
                $finalStr.=getBlogQuestions($course_id);
                $finalStr.="]}}";
            }
        } else if (preg_match("/^notificationsList/i", $list_id)) {
            $notif_id = $_GET['sid'];
            $notif = new Notification($notif_id);
            $finalStr.="{form:{title:'View notification', form_id:'viewNotif$notif_id', items:[";
            $finalStr.= "{label:{text:'" . $notif->from . ": " . $notif->message . "'}},";
            $finalStr.= "{checkbox:{id:'markRead',label:'Mark as read'}},";
            $finalStr.="]}}";
        } else if ($list_id == "blogQuestionList") {
            $blog_question_id = $_GET['sid'];
            $finalStr.=getViewBlogQuestion($blog_question_id);
        } else if ($list_id == "courseQuizList") {
            $course_id = $_GET['sid'];
            $finalStr.="{list:{title:'Select a Quiz', list_id:'quizList', items: [";
            $finalStr.=getQuizList($course_id, phoneNoToUserID($_GET['phone_number']));
            $finalStr.="]}}";
        } else if ($list_id == "lessonList") {
            $lesson_id = $_GET['sid'];
            $offset = 0;
            $finalStr.=prepareLessonPage($lesson_id, $offset);
        } else if ($list_id == "quizList") {
            $quiz_id = $_GET['sid'];
            $quiz = new Quiz($quiz_id);
            $title = $quiz->description;
            $finalStr.=prepareMobileQuestion($quiz_id,
                            phoneNoToUserID($_GET['phone_number']), "You must score " .
                            $quiz->pass_mark . " to pass this quiz");
        } else {
            $finalStr.="{form:{title:'Invalid', form_id:'Invalid', items:[";
            $finalStr.="{label:{text:'Invalid List submited $list_id, to save yourself, click the home button'}}";
            $finalStr.="]}}";
        }
    } else if ($state == "submit") {
        $form_id = $_GET['form_id'];
        if (preg_match("/^confirmEnroll/i", $form_id)) {
            $course_id = substr($form_id, strlen("confirmEnroll"));
            $finalStr.="{form:{title:'Enrollement', form_id:'enrollResult', items:[";
            $finalStr.="{label:{text:'" . enrollCourse(phoneNoToUserID($_GET['phone_number']), $course_id) . "'}}";
            $finalStr.="]}}";
        } else if (preg_match("/^question/i", $form_id)) {
            $params = substr($form_id, strlen("question"));
            $paramsArr = preg_split("/" . Sympols::$split5 . "/", $params);
//            var_dump($paramsArr);
            $quiz_id = $paramsArr[0];
            $question_id = $paramsArr[1];
            $system_answers = new SystemAnswers($question_id);
            $given_answers = new SubmittedAnswers($_GET, $system_answers->answers);
//            var_dump($given_answers);
//            var_dump($system_answers);
            if ($system_answers->correct_answer_count == $given_answers->num_of_given) {
                recordAnswers(phoneNoToUserID($_GET['phone_number']), $system_answers, $given_answers);
                $finalStr.=prepareMobileQuestion($quiz_id, phoneNoToUserID($_GET['phone_number']));
            } else {
                $finalStr.=prepareMobileQuestion($quiz_id, phoneNoToUserID($_GET['phone_number']), "Exactly " .
                                $system_answers->correct_answer_count . " answer(s) required");
            }
        } else if (preg_match("/^lessonContent/i", $form_id)) {
            $params = substr($form_id, strlen("lessonContent"));
            $paramsArr = preg_split("/" . Sympols::$split5 . "/", $params);
//            var_dump($paramsArr);
            $lesson_id = $paramsArr[0];
            $offset = (int) $paramsArr[2] + 1;
            $finalStr.=prepareLessonPage($lesson_id, $offset);
        } else if (preg_match("/^quizDone/i", $form_id)) {
            $quiz_id = substr($form_id, strlen("quizDone"));
            $title = getQuiz($quiz_id);
            $results = new Results($quiz_id);
            $finalStr.="{form:{title:'$title Quiz Done!', form_id:'results', items:[";
            if ($results->percentage > $results->pass_mark) {
                $finalStr.="{label:{text:'" . $results->percentage . "%. Congratulations you passed. You scored " . $results->score . " out " . $results->total_marks . " Correct!                                Press the back button to view other quizes.'}},";
                addNotification("$results->percentage%.Congratulations you passed. You scored " . $results->score . " out " . $results->total_marks . " Correct!", "System");
            } else {
                deleteAnswers($results->quiz_id);
                $finalStr.="{label:{text:'" . $results->percentage . "%.You failed against the passmark of $results->pass_mark%. You scored " . $results->score . " out " . $results->total_marks . " Correct!.  Please revise the content again and redo the quiz.'}},";
                addNotification("$results->percentage%. You failed against the passmark of $results->pass_mark%. You scored " . $results->score . " out " . $results->total_marks . " Correct!.  Please revise the content again and redo the quiz.", "System");
            }
            $finalStr.="]}}";
        } else if (preg_match("/^addBlogQuestion/i", $form_id)) {
            $course_id = substr($form_id, strlen("addBlogQuestion"));
            $question = $_GET['blogQuestionText'];
            addBlogQuestion($course_id, $question);
            $finalStr.=getBlogActionList($course_id, "Your topic has been added.");
        } else if (preg_match("/^viewBlogQuestion/i", $form_id)) {//show all replies inlcuding the add reply option
            $blog_question_id = substr($form_id, strlen("viewBlogQuestion"));
            $finalStr.="{form:{title:'Add comment', form_id:'addReply$blog_question_id', items:[";
            $finalStr.= "{textfield:{id:'blogReplyText',label:'Comment'}},";
            $finalStr.="]}}";
        } else if (preg_match("/^addReply/i", $form_id)) {//show all replies inlcuding the add reply option
            $blog_question_id = substr($form_id, strlen("addReply"));
            $reply = $_GET['blogReplyText'];
            addBlogReply($blog_question_id, $reply);
            $finalStr.=getViewBlogQuestion($blog_question_id, "Your reply has been added");
        } else if (preg_match("/^viewNotif/i", $form_id)) {//show all replies inlcuding the add reply option
            $notif_id = substr($form_id, strlen("viewNotif"));
            markNotifRead($notif_id);
            $finalStr.=getNotoficationsList("Notification has been removed from the list");
        } else if ($form_id == "termsAndConditions") {
            acceptCondtion();
            $finalStr.=getInteractionHome();
        } else {
            $finalStr.="{form:{title:'Invalid', form_id:'Invalid', items:[";
            $finalStr.="{label:{text:'Invalid submission, Click the home button'}}";
            $finalStr.="]}}";
        }
    }
    return $finalStr;
}